package com.project.nimsen.interceptor;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.util.WebUtil;

public class ProInterceptor implements HandlerInterceptor {
	@Resource
	WebUtil webUtil;
	@Resource
	FreeMarkerConfigurer configurer;
	@Resource
	IColtypeService coltypeService;
	boolean isparth = false;//表示没有把freemarker标签的路径放置到configurer里
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//判断用户终端类型
		boolean supper = true;
		String useagent = request.getHeader("User-Agent");
		if(StringUtils.isBlank(useagent))
			supper = false;
		else{
			if(useagent.contains("huaweip6-c00"))
				supper = true;
			if(useagent.contains("ipad"))
				supper = false;
			if(useagent.contains("iphone"))
				supper = false;
			if(useagent.contains("mac"))
				supper = false;
			if(useagent.contains("android"))
				supper = true;
		}
		request.setAttribute("supper", supper);
		
		
		//得到配置的web站点根目录
		WebUtil.webUrl(request);
		if(isparth){
			//把所有列表里的url全部添加到freemarker解析里
			List<Map<String, Object>> cols = coltypeService.finder(null);
			int size = cols.size();
			String [] strs = new String[size+1];
			for(int i=0;i<size;i++){
				Object vurl = cols.get(i).get("vurl");
				strs[i]="/pub/col"+vurl;
			}
			strs[size] = "/";
			configurer.setTemplateLoaderPaths(strs);
			configurer.setConfiguration(configurer.createConfiguration());
			isparth = false;
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
